<template>
  <div class="mod-config">
    <el-row :gutter="20">
      <!-- 分类树 -->
      <el-col :span="4">
        <div class="category-tree-container">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>素材分类</span>
            </div>
            <el-tree
              :data="categoryTree"
              :props="categoryTreeProps"
              node-key="categoryCode"
              :default-expanded-keys="defaultExpandedKeys"
              :expand-on-click-node="false"
              :current-node-key="selectedCategoryCode"
              @node-click="handleCategoryClick"
              ref="categoryTree">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span :class="{ 'selected-node': data.categoryCode === selectedCategoryCode }">{{ node.label }}</span>
              </span>
            </el-tree>
          </el-card>
        </div>
      </el-col>

      <!-- 素材列表 -->
      <el-col :span="20">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
          <el-form-item>
            <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList()">查询</el-button>
            <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
            <el-button type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
          </el-form-item>
          <el-form-item prop="materialImageUrl">
            <el-upload
              ref="upfileload"
              class="upload-demo"
              :data="dataObj"
              :action="dataObj.host"
              :auto-upload=true
              :before-upload="getImagePolicy"
              :on-success="handleImageUploadSuccess"
              list-type="picture">
              <el-button size="small" type="primary">选择图片</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column type="selection" header-align="center" align="center" width="50">
          </el-table-column>
          <el-table-column prop="gmtCreate" header-align="center" align="center" label="创建时间">
          </el-table-column>
          <el-table-column prop="materialCode" header-align="center" align="center" label="素材Code">
          </el-table-column>
          <el-table-column prop="materialName" header-align="center" align="center" label="素材名">
          </el-table-column>
<!--          <el-table-column prop="materialFileSize" header-align="center" align="center" label="素材大小">-->
<!--          </el-table-column>-->
          <el-table-column prop="materialFormat" header-align="center" align="center" label="格式">
          </el-table-column>
          <el-table-column prop="materialWidth" header-align="center" align="center" label="宽(px)">
          </el-table-column>
          <el-table-column prop="materialHeight" header-align="center" align="center" label="高(px)">
          </el-table-column>
          <el-table-column prop="materialUseRate" header-align="center" align="center" label="使用率">
          </el-table-column>
          <el-table-column prop="materialLabel" header-align="center" align="center" label="标签">
          </el-table-column>
          <el-table-column prop="materialImageUrl" header-align="center" align="center" label="预览图">
            <template slot-scope="scope">
              <div class="image-container">
                <img :src="scope.row.materialImageUrl" class="preview-image" @click="imagePreviewHandle(scope.row.materialImageUrl)"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="materialCategoryCode" header-align="center" align="center" label="分类code">
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
              <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" v-show="materialImageUrl!=''"
          layout="total, sizes, prev, pager, next, jumper">

        </el-pagination>
        <!-- 弹窗, 新增 / 修改 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
        <!-- 查看大图 -->
        <ImagePreview v-if="imagePreviewVisible" ref="imagePreview"  @refreshDataList="getDataList"></ImagePreview>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import AddOrUpdate from './wmhGalaxyMaterial-add-or-update'
import ImagePreview from '@/views/common/image-preview'
export default {
  data() {
    return {
      dataForm: {
        key: ''
      },
      dataObj: {
        policy: '',
        signature: '',
        OSSAccessKeyId: '',
        key: '',
        dir: '',
        host: '',
        expire: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      materialImageUrl:'',
      dataListSelections: [],
      addOrUpdateVisible: false,
      imagePreviewVisible: false,
      categoryTree: [],
      categoryTreeProps: {
        children: 'children',
        label: 'categoryName'
      },
      selectedCategoryCode: '',
      defaultExpandedKeys: [],
    }
  },

  components: {
    AddOrUpdate,
    ImagePreview
  },
  activated() {
    this.getCategoryTree()
  },
  methods: {
    // 获取分类树
    getCategoryTree() {
      this.$http({
        url: this.$http.adornUrl('/category/category/queryWormholeGalaxyCategoryList'),
        method: 'post',
        data: this.$http.adornData({
          isPage: false
        })
      }).then(({ data }) => {
        if (data && data.success) {
          this.categoryTree = data.data
          // 设置默认展开的节点
          this.setDefaultExpandedKeys()
          // 获取第一个最底层分类的数据
          this.$nextTick(() => {
            this.loadFirstLeafCategoryData()
          })
        } else {
          this.categoryTree = []
        }
      })
    },
    // 设置默认展开的节点
    setDefaultExpandedKeys() {
      if (this.categoryTree && this.categoryTree.length > 0) {
        // 默认展开第一个根节点
        this.defaultExpandedKeys = [this.categoryTree[0].categoryCode]
        // 递归展开第一个子节点直到最底层
        this.expandFirstPath(this.categoryTree[0])
      }
    },
    // 递归展开第一个路径直到最底层
    expandFirstPath(node) {
      if (node.children && node.children.length > 0) {
        // 展开第一个子节点
        const firstChild = node.children[0]
        this.defaultExpandedKeys.push(firstChild.categoryCode)
        // 继续展开第一个子节点的子节点
        this.expandFirstPath(firstChild)
      }
    },
    // 加载第一个最底层分类的数据
    loadFirstLeafCategoryData() {
      if (this.categoryTree && this.categoryTree.length > 0) {
        const firstLeafCategory = this.findFirstLeafCategory(this.categoryTree[0])
        if (firstLeafCategory) {
          this.selectedCategoryCode = firstLeafCategory.categoryCode
          this.$refs.categoryTree.setCurrentKey(this.selectedCategoryCode)
          this.getDataList()
        }
      }
    },
    // 查找第一个最底层分类
    findFirstLeafCategory(node) {
      if (!node.children || node.children.length === 0) {
        return node
      }
      return this.findFirstLeafCategory(node.children[0])
    },
    // 处理分类点击事件
    handleCategoryClick(data) {
      this.selectedCategoryCode = data.categoryCode
      this.$refs.categoryTree.setCurrentKey(this.selectedCategoryCode)
      this.pageIndex = 1
      this.getDataList()
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl(`/material/material/${!this.materialImageUrl ? 'queryWormholeGalaxyMaterialList' : 'queryWormholeGalaxyMaterialsByImageFromEs'}`),
        method: 'post',
        data: this.$http.adornData({
          isPage: this.materialImageUrl ? false : true,
          pageNumb: this.pageIndex,
          pageSize: this.pageSize,
          materialCategoryCode: this.selectedCategoryCode,
          materialImageUrl: this.materialImageUrl,
          key: this.dataForm.key
        })

      }).then(({ data }) => {
        if (data && data.success) {
          this.dataList = data.data
          this.totalPage = data.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
        this.clearData()
      })
    },
    // 获取上传策略
    getImagePolicy(file) {
      // 移除了文件类型和大小的限制检查
      return this.$http({
        url: this.$http.adornUrl('/oss/uploadByPolicy'),
        method: 'post',
        data: this.$http.adornData({
          "path": 'other',
        })
      }).then(({data}) => {
        if (data) {
          this.dataObj.key = data.data.dir + file.name
          this.dataObj.policy = data.data.policy
          this.dataObj.signature = data.data.signature
          this.dataObj.OSSAccessKeyId = data.data.accessKeyId
          this.dataObj.dir = data.data.dir
          this.dataObj.host = data.data.host
          this.dataObj.expire = data.data.expire
          };
      })
    },
    // 图片上传成功处理
    handleImageUploadSuccess(response, file, fileList) {
      this.materialImageUrl = this.dataObj.host+"/"+this.dataObj.key+"?x-oss-process=image/quality,q_3"
      console.log("图片上传"+this.materialImageUrl)
      this.makeSure = true
      this.$message.success('图片上传成功！');
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },

    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 查看大图
    imagePreviewHandle(url){
      this.imagePreviewVisible = true
      this.$nextTick(() => {
        this.$refs.imagePreview.init(url)
      })
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle(id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/material/material/deleteWormholeGalaxyMaterial'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    // 清除表单数据
    clearData() {
      // 重置表单数据

      this.materialImageUrl = ''
      // 清空上传文件列表
      if (this.$refs.upfileload) {
        this.$refs.upfileload.clearFiles()
      }
    },
  }
}
</script>

<style scoped>
.category-tree-container {
  margin-bottom: 20px;
}

.mod-config {
  padding: 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.selected-node {
  color: #409EFF;
  font-weight: bold;
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 120px;
}

.preview-image {
  max-width: 100px;
  max-height: 100px;
  cursor: pointer;
  object-fit: contain;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
  display: block;
}

.preview-image:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}
</style>
